package cn.nfwx.tv.controller.player;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.nfwx.tv.R;
import cn.nfwx.tv.controller.BusAnimController;
import cn.nfwx.tv.events.PlayEvents;
import cn.nfwx.tv.fragment.me.MineFragment;
import cn.nfwx.tv.fragment.search.SearchFragment;
import cn.nfwx.tv.helper.AccountHelper;
import cn.nfwx.tv.helper.ActivityHelper;
import cn.nfwx.tv.helper.DialogFragmentHelper;
import cn.nfwx.tv.helper.NetworkHelper;
import cn.nfwx.tv.helper.ThreadHelper;
import cn.nfwx.tv.manager.QpopManager;
import cn.nfwx.tv.manager.WatchRecordManager;
import cn.nfwx.tv.model.QpopChannel;
import cn.nfwx.tv.model.QpopProgram;
import cn.nfwx.tv.okhttp.UrlHelper;
import cn.nfwx.tv.util.AnimationUtil;
import cn.nfwx.tv.util.AppUtil;
import cn.nfwx.tv.util.SharePrefUtil;
import cn.nfwx.tv.util.TimeUtil;
import cn.nfwx.tv.util.ToastUtil;
import cn.nfwx.tv.widget.QpopReviewView;
import cn.nfwx.tv.widget.nfwxplayer.NfwxVideoPlayerManager;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class BusPlayerController extends BasePlayerController implements QpopReviewView.QpopReviewItemClickListener {

    private String requestQpopPlayListCommand, requestQpopVodCommand;
    private List<QpopChannel.DataBean.Channel> busChannels = new ArrayList<>();
    private int _position = -1;
    private boolean _isLive = true;
    private String onShot;

    public BusPlayerController(@NonNull Context context) {
        super(context);
    }

    private void loadData() {
        if (busChannels.isEmpty()) {
            requestQpopPlayListCommand = QpopManager.requestQpopPlayList(callback);
        } else {
            play(0);
        }
    }


    @Override
    protected void backLive() {
        if (!isLive()) {
            // 手动隐藏广告
            NfwxVideoPlayerManager.instance().suspendVideoPlayer();
            refreshView(false);
            ThreadHelper.postDelayed(new Runnable() {
                @Override
                public void run() {
                    refreshView(true);
                    ll_bottom.setVisibility(View.VISIBLE);
                    pcv_home.showTvprogram();
                    tv_vodplayer_back.setText("直播");
                    _isLive = true;
                    reStart();
                }
            }, durationMillis + 100);
        }
    }

    @Override
    protected boolean isDownedPlay() {
        return false;
    }

    @Override
    protected void openProgram() {
        if (_isReview) {
            return;
        }
        super.openProgram();
        findView(R.id.review_btn).setClickable(false);
        ThreadHelper.postDelayed(new Runnable() {
            @Override
            public void run() {
                findView(R.id.review_btn).setClickable(true);
                AnimationUtil.startSlideFromRightAnimation(qrv_review, 300, null);
                qrv_review.setVisibility(View.VISIBLE);
                _isReview = true;
            }
        }, 300);

    }

    @Override
    protected void initView() {
        super.initView();
        initReview();
        ll_titlebar.setVisibility(View.GONE);
        qrv_review.setItemClickListener(this);

        BusAnimController.getInstance().auth(mContext);
        player_bar.showQpopWIFI();
    }

    /**
     * 初始化回看
     */
    private void initReview() {
        List<String> dates = new ArrayList<>();
        dates.add(TimeUtil.getTodayMMdd(-3));
        dates.add(TimeUtil.getTodayMMdd(-2));
        dates.add(TimeUtil.getTodayMMdd(-1));
        dates.add("今天");
        dates.add(TimeUtil.getTodayMMdd(1));
        qrv_review.setNewDates(dates);
    }

    @Override
    protected void initData() {
        loadData();
    }

    @Override
    public void playBack() {
        refreshView(true);
        autoActionHidden();
        if (isLive()) {
            if (_position == 0) {
                if (busChannels.isEmpty()) {
                    return;
                }
                play(busChannels.size() - 1);
            } else {
                play(_position - 1);
            }
        }
    }

    @Override
    public void playNext() {
        refreshView(true);
        autoActionHidden();
        if (isLive()) {
            if (busChannels.isEmpty()) {
                play(0);
                return;
            }
            if (_position == busChannels.size() - 1) {
                play(0);
            } else {
                play(_position + 1);
            }
        }
    }

    @Override
    public boolean isLive() {
        return _isLive;
    }

    @Override
    public boolean isAdvert() {
        return false;
    }

    @Override
    public boolean isShift() {
        return false;
    }

    @Override
    public boolean isAudio() {
        return false;
    }

    @Override
    public boolean isClip() {
        return false;
    }

    @Override
    public String getTimesShiftUrl(long timeCode) {
        return null;
    }

    @Override
    public void reStart() {
        if (isLive()) {
            if (busChannels.isEmpty()) {
                onShot = "";
                loadData();
            } else {
                final int i = _position;
                _position = -1;
                onShot = "";
                play(i);
            }
        } else {
            final String path = onShot;
            onShot = "";
            doPlayVideo(path);
        }
    }

    @Override
    protected void openReview() {
        if (_isReview) {
            return;
        }
        super.openReview();
        findView(R.id.review_btn).setClickable(false);
        refreshView(false);
        ThreadHelper.postDelayed(new Runnable() {
            @Override
            public void run() {
                findView(R.id.review_btn).setClickable(true);
                AnimationUtil.startSlideFromRightAnimation(qrv_review, 300, null);
                qrv_review.setVisibility(View.VISIBLE);
                _isReview = true;
            }
        }, 300);
    }

    Callback callback = new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            String requestCommand = (String) call.request().tag();
            if (requestCommand.equals(requestQpopVodCommand)) {
                ThreadHelper.post(new Runnable() {
                    @Override
                    public void run() {
                        qrv_review.loadError();
                    }
                });
            } else if (requestCommand.equals(requestQpopPlayListCommand)) {
                ThreadHelper.post(new Runnable() {
                    @Override
                    public void run() {
                        loadview.loadError(view_player);
                    }
                });
            }
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            String requestCommand = (String) call.request().tag();
            if (requestCommand.equals(requestQpopPlayListCommand)) {
                if (response.code() == 200) {
                    String str = response.body().string();
                    String jsonStr = str.substring(str.indexOf("callback(") + 9, str.lastIndexOf(")"));
                    final QpopChannel qpopChannel = JSON.parseObject(jsonStr, QpopChannel.class);
                    ThreadHelper.post(new Runnable() {
                        @Override
                        public void run() {
                            loadview.removeParentView(view_player);
                            busChannels.clear();
                            busChannels.addAll(qpopChannel.getData().getList());
                            channelAdapter.setNewData(new ArrayList<Object>(qpopChannel.getData().getList()));
                            play(0);
                        }
                    });
                } else {
                    ThreadHelper.post(new Runnable() {
                        @Override
                        public void run() {
                            loadview.removeParentView(view_player);
                        }
                    });
                }
            } else if (requestCommand.equals(requestQpopVodCommand)) {
                String str = response.body().string();
                if (response.code() == 200) {
                    JSONObject data = JSON.parseObject(str);
                    JSONObject Data = data.getJSONObject("Data");
                    String channelStr = Data.getString("data");
                    final List<QpopProgram> reviewProgram = JSON.parseObject(channelStr, new TypeToken<List<QpopProgram>>() {
                    }.getType());

                    ThreadHelper.post(new Runnable() {
                        @Override
                        public void run() {
                            qrv_review.setNewPrograms(reviewProgram);
                        }
                    });
                }
            }
        }
    };

    /**
     * 播放视频
     *
     * @param position
     */
    private void play(int position) {
        if (_position != position && !busChannels.isEmpty()) {
            QpopChannel.DataBean.Channel channel = busChannels.get(position);
            title_channel_name.setText(channel.getTitle());
            channelAdapter.setSelected(position);
            recyclerViewHelper.smoothScrollToPositionCenter(position);
            channelAdapter.notifyDataSetChanged();
            _position = position;
            _isLive = true;
            autoActionHidden();
            qrv_review.clearDate();
            qrv_review.clearPrograms();
            getVods(channel.getId(), TimeUtil.getToday());
            // 初始化进度条
            doPlayVideo(channel.getPlayUrl());
        }
    }

    /**
     * 点播
     *
     * @param program
     */
    private void play(final QpopProgram program) {
        if (program.getIsPlaying() == 0) { // 如果是直播频道，返回直播
            final int postion = _position;
            _position = -1;
            play(postion);
            if (_isReview) {
                _isReview = false;
                AnimationUtil.startSlideToRightAnimation(qrv_review, 300, null);
                qrv_review.setVisibility(View.GONE);
            }
            ThreadHelper.postDelayed(new Runnable() {
                @Override
                public void run() {
                    refreshView(true);
                    pcv_home.setVisibility(View.GONE);
                    ll_bottom.setVisibility(View.VISIBLE);
                    tv_vodplayer_back.setVisibility(View.GONE);
                    vodplayer_back_btn.setVisibility(View.GONE);
                    tv_qpop_quit.setVisibility(View.GONE);
                    iv_qpop_quit.setVisibility(View.VISIBLE);
                    findView(R.id.review_btn).setVisibility(View.VISIBLE);
                }
            }, 500);
        } else if (!program.getVideoUrl().equals(onShot) && program.getVideoValid() == 1) {
            _isLive = false;
            _isReview = false;
            pcv_home.playView();
            title_channel_name.setText(program.getActname());
            AnimationUtil.startSlideToRightAnimation(qrv_review, 300, null);
            qrv_review.setVisibility(View.GONE);
            ThreadHelper.postDelayed(new Runnable() {
                @Override
                public void run() {
                    refreshView(!_isShow);
                    pcv_home.setVisibility(View.VISIBLE);
                    ll_bottom.setVisibility(View.GONE);
                    tv_qpop_quit.setVisibility(View.GONE);
                    iv_qpop_quit.setVisibility(View.GONE);
                    tv_vodplayer_back.setVisibility(View.VISIBLE);
                    vodplayer_back_btn.setVisibility(View.VISIBLE);
                    findView(R.id.review_btn).setVisibility(View.GONE);
                }
            }, 500);

            autoActionHidden();
            doPlayVideo(program.getVideoUrl());
        }
    }

    /**
     * 播放
     *
     * @param path
     */
    private void doPlayVideo(String path) {
        if (!path.equals(onShot)) {
            changeLiveView();
            if (isLive()) {
                findView(R.id.review_btn).setVisibility(View.VISIBLE);
                findView(R.id.download_btn).setVisibility(View.GONE);
                findView(R.id.clip_btn).setVisibility(View.GONE);
                findView(R.id.share_btn).setVisibility(View.GONE);
                pcv_home.setVisibility(View.GONE);
            } else {
                findView(R.id.clip_btn).setVisibility(View.GONE);
                findView(R.id.download_btn).setVisibility(View.GONE);
                findView(R.id.review_btn).setVisibility(View.GONE);
                findView(R.id.share_btn).setVisibility(View.GONE);
            }
            findView(R.id.iv_advertise).setVisibility(View.GONE);
            onShot = path;
            mNfwxVideoPlayer.releasePlayer();
            mNfwxVideoPlayer.setUp(path, null);
            mNfwxVideoPlayer.start();
        }
    }

    /**
     * 获取回看视频
     *
     * @param lid
     * @param date
     */
    public void getVods(int lid, String date) {
        requestQpopVodCommand = QpopManager.requestQpopVodList(lid, date, callback);
    }

    @Override
    public void dateItemClick(String dateStr) {
        QpopChannel.DataBean.Channel channel = busChannels.get(_position);
        getVods(channel.getId(), dateStr);
    }

    @Override
    public void programItemClick(QpopProgram program) {
        play(program);
    }

    /**
     * 直播切换节目
     *
     * @param view
     * @param position
     */
    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        channelAdapter.setSelected(position);
        play(position);
    }
}
